package com.shitou.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;

import com.octo.captcha.service.CaptchaServiceException;
import com.shitou.service.CaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CaptchaAction extends SimpleBaseAction{

	private static final long serialVersionUID = 1L;
	private String id;

	@Override
	public String execute() throws Exception {
		byte[] captchaChallengeAsJpeg = null;
        // the output stream to render the captcha image as jpeg into
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // get the session id that will identify the generated captcha.
            //the same id must be used to validate the response, the session id is a good candidate!
            String captchaId = getRequest().getSession().getId();
            // call the ImageCaptchaService getChallenge method
            BufferedImage challenge =
                    CaptchaService.getInstance().getImageChallengeForID(captchaId,
                            getRequest().getLocale());
            // a jpeg encoder
            JPEGImageEncoder jpegEncoder =
                    JPEGCodec.createJPEGEncoder(jpegOutputStream);
            jpegEncoder.encode(challenge);
        } catch (IllegalArgumentException e) {

        	return null;
        } catch (CaptchaServiceException e) {

        	return null;
        }
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        // flush it in the response
        getResponse().setHeader("Cache-Control", "no-store");
        getResponse().setHeader("Pragma", "no-cache");
        getResponse().setDateHeader("Expires", 0);
        getResponse().setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
        	getResponse().getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
        
        return null;
    }

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
}
